package app.dev.ems.config.database;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import app.dev.ems.data.model.impl.User;

public class SchemaValidator {

	private SessionFactory sessionFactory;
	private SchemaHelper schemaHelper;
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	public void validate() {
		Session session = sessionFactory.openSession();
		try {
			session.createCriteria(User.class).add(Restrictions.eq("username", "admin")).list().get(0);
			logger.info("Database schema exists");
		} catch(Exception exception) {
			logger.info("Database schema does not exist. Will be created.");
			schemaHelper.createSchema();
			logger.info("Schema created. Inserting Admin");
			User admin = new User();
			admin.setUsername("admin");
			admin.setPassword("admin");
			session.save(admin);			
			logger.info("Admin inserted sucessfully");
		}				
	}
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	public SchemaHelper getSchemaHelper() {
		return schemaHelper;
	}
	public void setSchemaHelper(SchemaHelper schemaHelper) {
		this.schemaHelper = schemaHelper;
	}		
}
